package com.tech.koufu.ui.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.login.LoginActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 行情详情页面
 * @author eric
 *
 */
public class MarketDeatilActivity extends Activity implements OnClickListener{
	private static final String TAG = MarketDeatilActivity.class.getName();
	private ImageView img_callback;
	private ImageView img_addchoose;
	private TextView tv_title;
	private TextView tv_addchoose;
	private RelativeLayout item_header;
	private LinearLayout tab_market;
	private LinearLayout ly_buy,ly_sell,ly_addchoose;
	private WebView wb_mk_dt;
	private ProgressBar pb_wait;
	//	private UserStocks mUserStocks;
	private String stock_code;
	private String stock_name;
	private String inZixuangu;
	private boolean isChoose;
	//	private RequestQueue mQueue; 
	//	CookieStringRequest stringRequest;
	private MyApplication myApp;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_marketdetail);
		context = getApplicationContext();
		stock_code = getIntent().getStringExtra("stockCode");
		stock_name = getIntent().getStringExtra("stockName");
		inZixuangu = getIntent().getStringExtra("inZixuangu");

		initView();
		if(stock_code.equals("000001")&& stock_name.equals("上证指数")||stock_code.equals("399001") || stock_code.equals("399006")){
			ly_buy.setVisibility(View.GONE);
			ly_sell.setVisibility(View.GONE);
		}
		mychoose();
		loadWebView(stock_code);
	}

	private void initView(){
		myApp = (MyApplication)getApplication();
		//		mQueue = Volley.newRequestQueue(getApplicationContext());  
		item_header = (RelativeLayout)findViewById(R.id.item_header);
		item_header.bringToFront();
		tab_market = (LinearLayout)findViewById(R.id.tab_market);
		tab_market.bringToFront();
		img_callback = (ImageView)findViewById(R.id.img_callback);
		img_callback.setVisibility(View.VISIBLE);
		img_callback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(wb_mk_dt.canGoBack()){
					wb_mk_dt.goBack();
				}else{
					MarketDeatilActivity.this.finish();
				}				
			}
		});
		tv_title = (TextView)findViewById(R.id.tv_title);
		tv_title.setVisibility(View.VISIBLE);
		tv_title.setText(stock_name + "\n" + stock_code);
		tv_title.setTextSize(15);
		wb_mk_dt = (WebView)findViewById(R.id.wb_mk_dt);
		pb_wait = (ProgressBar)findViewById(R.id.pb_wait);

		img_addchoose = (ImageView)findViewById(R.id.img_addchoose);
		tv_addchoose = (TextView)findViewById(R.id.tv_addchoose);
		ly_buy = (LinearLayout)findViewById(R.id.ly_buy);
		ly_sell = (LinearLayout)findViewById(R.id.ly_sell);
		ly_addchoose = (LinearLayout)findViewById(R.id.ly_addchoose);
		ly_addchoose.setOnClickListener(this);
		ly_buy.setOnClickListener(this);
		ly_sell.setOnClickListener(this);

	}

	private void mychoose(){
		if(inZixuangu!=null && !inZixuangu.equals("")){
			if(inZixuangu.equals("yes")){
				img_addchoose.setImageResource(R.drawable.mychoose_check);
				tv_addchoose.setText("删除自选");
				isChoose = true;
			}else{
				img_addchoose.setImageResource(R.drawable.mychoose_uncheck);
				tv_addchoose.setText("加入自选");
				isChoose = false;
			}
		}
	}

	private void loadWebView(String stockCode){
		String market;
		if (stockCode.equals("000001") && stock_name.equals("上证指数")) {
			market = "SH";
		}else{
			market = KouFuTools.getEnCode(stockCode);
		}

		String url = "https://i.gtja.com/quotes/quotes/detail.html?stockCode="
				+stockCode + "&market="+market;
		//		String url = "https://i.gtja.com/quotes/quotes/detail.html?stockCode=000001&market=SH";
		WebSettings webSettings = wb_mk_dt.getSettings();
		webSettings.setDomStorageEnabled(true);
		webSettings.setDatabaseEnabled(true);    
		String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
		wb_mk_dt.getSettings().setJavaScriptEnabled(true);
		wb_mk_dt.getSettings().setBuiltInZoomControls(false);
		wb_mk_dt.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
				pb_wait.bringToFront();
				pb_wait.setVisibility(View.VISIBLE);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				pb_wait.setVisibility(View.GONE);
			}
		});
		wb_mk_dt.loadUrl(url);
	}

	private void loadMyChoose(){
		String choose;
		if(isChoose){
			choose = Statics.IF_removechoose;
		}else{
			choose = Statics.IF_addchoose;
		}
		String url = Statics.URL_PHP + choose;

		CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				if(!TextUtils.isEmpty(response)){
					try {
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							Toast.makeText(getApplicationContext(), obj.getString("data"), Toast.LENGTH_SHORT).show();
							if(isChoose){
								img_addchoose.setImageResource(R.drawable.mychoose_uncheck);
								isChoose = false;
							}else{
								img_addchoose.setImageResource(R.drawable.mychoose_check);
								isChoose = true;								
							}
						}else{
							Toast.makeText(getApplicationContext(), obj.getString("data"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		},new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}){		
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("userID", myApp.digitalid);//userid 
				params.put("stock_code", stock_code);
				params.put("stock_name", stock_name);
				return params;
			}
		};
		stringRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && wb_mk_dt.canGoBack()) {  
			wb_mk_dt.goBack();  
			return true;
		}else{
			MarketDeatilActivity.this.finish();
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ly_addchoose:
			if(myApp.isLogin){
				loadMyChoose();
			}else{
				Toast.makeText(getApplicationContext(), "请先登录！", Toast.LENGTH_SHORT).show();
				toLoginPage();				
			}
			break;
		case R.id.ly_buy:
			if(myApp.isLogin){
				buyORsell(0);
			}else{
				Toast.makeText(getApplicationContext(), "请先登录！", Toast.LENGTH_SHORT).show();
				toLoginPage();
			}
			break;
		case R.id.ly_sell:
			if(myApp.isLogin){
				boolean isToast = true;
				if(myApp.mUserStocks !=null &&myApp.mUserStocks.size()>0){
					for(int i = 0 ; i< myApp.mUserStocks.size() ; i ++){
						if(stock_code.equals(myApp.mUserStocks.get(i).stockId)){
							Intent intent = new Intent(getApplicationContext(),BuyStocksActivity.class);
							intent.putExtra("stockInfo", myApp.mUserStocks.get(i));
							intent.putExtra("type", 1);
							startActivity(intent);
							MarketDeatilActivity.this.finish();
							isToast = false;
						}
					}

					if(isToast){
						Toast.makeText(getApplicationContext(), "您未持有当前股票，不可执行该操作！", Toast.LENGTH_SHORT).show();
						isToast = false;
					}
				}
				//				else{
				//					Toast.makeText(getApplicationContext(), "您未持有当前股票，不可执行该操作！", Toast.LENGTH_SHORT).show();
				//				}

			}else{
				Toast.makeText(getApplicationContext(), "请先登录！", Toast.LENGTH_SHORT).show();
				toLoginPage();
			}
			break;
		default:
			break;
		}
	}

	private void toLoginPage(){
		setResult(1);
		Intent intent = new Intent();
		intent.setClass(MarketDeatilActivity.this, LoginActivity.class);
		startActivity(intent);
		MarketDeatilActivity.this.finish();
	}

	private void buyORsell(int type){
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), BuyStocksActivity.class);
		intent.putExtra("type", type);
		intent.putExtra("parsetype", 3);
		intent.putExtra("code", stock_code);
		intent.putExtra("name", stock_name);
		startActivity(intent);
		MarketDeatilActivity.this.finish();
	}
	@Override
	protected void onStop() { 
		super.onStop();
		RequestQueueSingleton.getInstance(context).cancleAllReq(TAG);

	}
}
